package com.ransj.iphone;

import com.ransj.iphone.utils.ILog;
import com.ransj.iphone.utils.ITracker;
import com.ransj.iphone.utils.Isp;
import com.ransj.iphone.view.ViewHolder;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.WindowManager;
/**
 * Iservice
 * @author ranshengju
 *
 */
public class Iservice extends Service{
	private static final String TAG = Iservice.class.getSimpleName();
	public static final String ACTION_SHOW_MAIN = "action_show_main";
	private ViewHolder mViewHolder;
	private ITracker mTracker;
	private int mOrientation;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mTracker = new ITracker(this);
		mViewHolder = ViewHolder.getInstance();
		mViewHolder.init(getApplicationContext(),
				(WindowManager) getSystemService(Activity.WINDOW_SERVICE),
				mTracker);
		Isp.getInstance(getApplicationContext());
		ILog.getInstance().w("TAG", "code path : "+getPackageCodePath());
		init(this);
		mOrientation = getResources().getConfiguration().orientation;
	}
	

	@Override
	public void onStart(Intent intent, int startId) {
		if(intent != null){
			String action = intent.getAction();
			ILog.getInstance().w("TAG", "onStart ... "+action);
			if(!TextUtils.isEmpty(action) && action.equals(ACTION_SHOW_MAIN)){
				mViewHolder.createMainView();
			}
		}
	}
	
	@Override
	public void onDestroy() {
		mTracker.stopTrack();
		super.onDestroy();
		ILog.getInstance().close();
		Intent restart = new Intent(this, Iservice.class);
		startService(restart);
	}
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		ILog.getInstance().w(TAG, "onConfigurationChanged ORIENTATION_LANDSCAPE : "+(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE));
		ILog.getInstance().w(TAG, "onConfigurationChanged ORIENTATION_PORTRAIT : "+(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT));
		if(newConfig.orientation != mOrientation){
			mOrientation = newConfig.orientation;
			mViewHolder.onConfigurationChanged(newConfig);
		}
	}



	static {
		try {
			System.loadLibrary("iphone");
		} catch (Exception e) {
			ILog.getInstance().e(TAG, e);
		}
	}
	
	private native void init(Context context);

}
